package com.team06.util;

import com.team06.pojo.Airl;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AirlXmlParserUtil {
    private static final Logger LOGGER = Logger.getLogger(AirlXmlParserUtil.class.getName());

    public static Airl parseXml(String xmlPath) {
        Airl entity = new Airl();
        try {
            File file = new File(xmlPath);
            SAXBuilder saxBuilder = new SAXBuilder();
            Document document = saxBuilder.build(file);
            Element root = document.getRootElement();

            // 解析 META 节点
            Element metaElement = root.getChild("META");
            if (metaElement != null) {
                entity.setSender(metaElement.getChildText("SNDR"));
                entity.setReceiver(metaElement.getChildText("RCVR"));
                entity.setSequence(Integer.parseInt(metaElement.getChildText("SEQN")));
                entity.setDtime(metaElement.getChildText("DDTM"));
                entity.setMtype(metaElement.getChildText("TYPE"));
                entity.setStype(metaElement.getChildText("STYP"));
            }

            // 解析 DFLT 节点
            Element dfltElement = root.getChild("DFLT");
            if (dfltElement != null) {
                entity.setDfltFlid(Integer.parseInt(dfltElement.getChildText("FLID")));
                entity.setDfltFide(dfltElement.getChildText("FIDE"));
                entity.setDfltFfid(dfltElement.getChildText("FFID"));

                // 解析 AIRL 节点下的多个 ARPT 节点
                Element airlElement = dfltElement.getChild("AIRL");
                if (airlElement != null) {
                    StringBuilder airlArptIdBuilder = new StringBuilder();
                    List<Element> arptElements = airlElement.getChildren("ARPT");

                    for (int i = 0; i < arptElements.size(); i++) {
                        Element arptElement = arptElements.get(i);
                        String apcd = arptElement.getChildText("APCD");
                        String apat = arptElement.getChildText("APAT");

                        if (i > 0) {
                            airlArptIdBuilder.append(",");
                        }
                        airlArptIdBuilder.append(apcd).append(":").append(apat);
                    }

                    entity.setAirlArptId(airlArptIdBuilder.toString());
                }
            }
        } catch (JDOMException | IOException | NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Failed to parse XML file: " + xmlPath, e);
            return null;
        }
        return entity;
    }
}